#include "LinkedStack.h"
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
// 创建一个空栈
struct LinkedStack*Create_Stack()
{
    struct LinkedStack*s = malloc(sizeof(*s));
    if(s == NULL)
        return NULL;
    s->num = 0;
    s->bottom = s->top = NULL;

    return s;
}
// 清空栈
bool Clear_Stack(struct LinkedStack*s)
{
    if(s == NULL)
        return false;
    if(Is_Empty(s))
        return true;
    struct Node*p = s->bottom;//指向栈底
    while(p)
    {
        s->bottom = s->bottom->next;
        if(s->bottom)
            s->bottom->pre = NULL;
        p->next = NULL;
        free(p);
        p = s->bottom ;
    }
    s->top = NULL;
    s->num = 0;

    return true;
}
// 销毁一个栈
bool Destroy_Stack(struct LinkedStack*s)
{
    if(s == NULL)
       return false;
    // if(!Clear_Stack(s))
    // {
    //     return false;
    // }
    Clear_Stack(s);
    free(s);
    s = NULL;
    return true;
}
// 判断栈是否为空
bool Is_Empty(struct LinkedStack*s)
{
    if(s == NULL)
    {
        return false;
    }

    return s->num == 0 && s->bottom == NULL && s->top == NULL ? true : false;
}
// 获取栈的长度:元素个数
int Get_Length(struct LinkedStack*s)
{
    if(s == NULL)
        return -1;
    return s->num;
}
// 出栈
bool Pop(struct LinkedStack*s, SElemType* d)
{
    if(s == NULL || Is_Empty(s))
        return false;
    
    struct Node*p = s->top;//指向要删除的节点
    if(d)
        *d = p->data;
    s->top = p->pre;//s->top = s->top->pre;
    if(s->top)
        s->top->next = NULL;
    else
        s->bottom = NULL;
    p->pre = NULL;
    free(p);
    p = NULL;

    s->num--;

    return true;

}
// 入栈
bool Push(struct LinkedStack*s, SElemType d)
{
    if(s == NULL)
        return false;
    //创建新节点并赋值
    struct Node*pnew = malloc(sizeof(*pnew));
    if(pnew == NULL)
        return false;
    pnew->data = d;
    pnew->next = pnew->pre = NULL;

    if(Is_Empty(s))
    {
        s->bottom = s->top = pnew;
    }
    else
    {
        pnew->pre = s->top;
        s->top->next = pnew;
        s->top = pnew;//更新栈顶指针
    }
    s->num++;

    return true;
}
// 获取栈顶元素，但不出栈
bool Get_Top(struct LinkedStack*s, SElemType* d)
{
    if(s == NULL || Is_Empty(s))
        return false;
    
   
    if(d)
        *d = s->top->data;
   

    return true;

}

